<template>
	<view class="test">
		<!-- <image src="http://applet.atptest.com/test.jpeg" mode="widthFix"></image> -->
		<view class="main">
			<u--form ref="form" :model="formData" :rules="rules" labelPosition="left">
				<view class="table">
					<view class="head">
						检测详情
					</view>
					<view class="body">
						<view>
							<u-form-item label="委托方:" labelWidth="120rpx" prop="client" :required="true">
								<u--input v-model="formData.client" placeholder="请输入委托方" border="none"></u--input>
							</u-form-item>
						</view>
						<view>
							<u-form-item label="供应商:" labelWidth="120rpx" prop="supplier">
								<u--input v-model="formData.supplier" placeholder="请输入供应商" border="none"></u--input>
							</u-form-item>
						</view>
					</view>
					<view class="body">
						<view>
							<u-form-item label="型号:" labelWidth="120rpx">
								<u--input v-model="formData.model" placeholder="请输入型号" border="none"></u--input>
							</u-form-item>
						</view>
						<view>
							<u-form-item label="批次:" labelWidth="120rpx" prop="batch">
								<u--input v-model="formData.batch" placeholder="请输入批次" border="none"></u--input>
							</u-form-item>
						</view>
					</view>
					<view class="body">
						<view style="position: relative;">
							<u-form-item label="品牌:" labelWidth="120rpx" prop="brandName">
								<u--input v-model="formData.brandName" placeholder="请输入品牌" border="none"
									@input="inputBrand()" @focus="focusBrand()" @blur="blurBrand()"></u--input>
							</u-form-item>
							<fuzzy-list label-name="name" value-name="id" align="center" no-data="无匹配项"
								:show="showFuzzy" :list="listFuzzy" :custom-style="{ fontSize: '20rpx' }"
								@select="selectFuzzy"></fuzzy-list>
						</view>
						<view style="position: relative;">
							<u-form-item label="产地:" labelWidth="120rpx" prop="production">
								<u--input v-model="formData.production" placeholder="请输入产地" border="none"
									@input="inputBrandP()" @focus="focusBrandP()" @blur="blurBrandP()"></u--input>
							</u-form-item>
							<fuzzy-list label-name="name" value-name="id" align="center" no-data="无匹配项"
								:show="showFuzzyP" :list="listFuzzyP" :custom-style="{ fontSize: '20rpx' }"
								@select="selectFuzzyP"></fuzzy-list>
						</view>
					</view>
					<view class="body">
						<view>
							<u-form-item label="数量:" labelWidth="120rpx" prop="sCount" :required="true">
								<u--input type="number" v-model="formData.sCount" placeholder="请输入订单数量" border="none">
								</u--input>
							</u-form-item>
						</view>
						<view>
							<u-form-item v-if="role.id == 1 || role.id == 2" label="采购单号:" labelWidth="120rpx"
								prop="purchaseOrderNo" :required="true">
								<u--input v-model="formData.purchaseOrderNo" placeholder="请输入采购单号" border="none">
								</u--input>
							</u-form-item>
						</view>
					</view>
				</view>
				<view class="table">
					<view class="head">
						检测项目
					</view>
					<view class="body1">
						<view class="fristChild" v-for="(item, index) in checkbox" :key="item.id">
							<view class="name">
								{{item.name}}
							</view>
							<view class="price">
								<text style="color: #A80000;padding-left: 2px;">￥{{item.price}}</text>
							</view>
							<view class="number">
								<u-icon name="minus" color="#000" size="12" @click="decreaseNum(item)"></u-icon>
								<span>{{item.amount}}</span>
								<u-icon name="plus" color="#000" size="12" @click="addNum(item)"></u-icon>
							</view>
						</view>
						<view class=" secondChild">
							<u-checkbox-group v-model="reportTypeValue" shape="square" size="24rpx"
								@change="checkboxChange">
								<u-checkbox v-for="(item,index) in reportType" :key="index" :name="item.id"
									:label="item.name + '('+ '￥'+item.price+')'" labelSize="24rpx"
									:customStyle="{marginRight: '8px'}">
								</u-checkbox>
							</u-checkbox-group>
						</view>
						<view class="note">
							<view>备注：</view>
							<view>
								<u--input v-model="formData.remark" placeholder="请输入备注" border='none'></u--input>
							</view>
						</view>
					</view>
				</view>
				<view style="color: red;font-size: 18rpx;">特殊说明: 检测服务费不包含出具检测详细报告费用，检测报告费用另外收取100/份</view>

				<view class="mailType">
					<view style="font-weight: 700;">请选择寄件方式</view>
					<u-radio-group v-model="formData.addressType" wrap="true" placement="column">
						<view class="box" v-for="(item,index) in mailType" :key="index" @click="openClick(index)">
							<view>
								<view>{{item.name}}</view>
								<view style="font-size: 20rpx;margin-top: 10rpx;">{{item.text}}</view>
							</view>
							<view>
								<u-radio :name="item.id" @change="openClick(index)"></u-radio>
							</view>
						</view>
					</u-radio-group>
				</view>

				<!-- 选择优惠券 -->
				<view class="coupon_container" @click="toDiscount()">
					<view style="display: flex;align-items: center;">
						<text>优惠券选择</text>
						<image style="width: 42rpx;padding-left: 14rpx;" src="http://applet.atptest.com/23042306.png"
							mode="widthFix"></image>
					</view>

					<view v-if="couponType != -1" style="font-size: 24rpx;">
						<text style="background-color: #3E56BA;color: #fff;border-radius: 10rpx;padding: 2rpx 16rpx;"
							v-if="couponType == 0">满减券 x 1</text>
						<text style="background-color: #fcc524;color: #fff;border-radius: 10rpx;padding: 2rpx 16rpx;"
							v-if="couponType == 1">现金券 x 1</text>
						<text style="background-color: #1ed76d;color: #fff;border-radius: 10rpx;padding: 2rpx 16rpx;"
							v-if="couponType == 2">免费券 x 1</text>
					</view>

					<view style="display: flex;font-size: 24rpx;justify-content: space-around;">
						<text style="color: #BB645A;" v-if="discounts">-￥{{discounts}}</text>
						<u-icon name="arrow-right"></u-icon>
					</view>
				</view>

				<view style="font-size: 24rpx;margin: 40rpx 0; ">
					<u-radio-group v-model="readValue">
						<u-radio :name="1" shape="square">
							<span style="color: #AEAEAE;">阅读并同意</span>
							<span style='font-weight: 700;' @click="openClick(8)">《鹏城测试服务协议》</span>
							<!-- <span>及</span>
							<span style='font-weight: 700;' @click="openClick(9)">《鉴别规则》</span> -->
						</u-radio>
					</u-radio-group>
				</view>
				<button @click="formSubmit" :disabled="btnDisabled" v-if="isUrgentFlag"
					style="width: 100%; color: #fff;background-color: #3953b8;margin-bottom: 40rpx;">立即支付（￥{{formData.total}}）</button>
				<button @click="showReserveTime" :disabled="btnDisabled" v-else
					style="width: 100%;color: #fff;background-color: #3953b8;margin-bottom: 40rpx;">选择时间</button>
			</u--form>
		</view>

		<u-toast ref="uToast"></u-toast>

		<!-- 通知弹出层 -->
		<u-popup :show="show" :round="30" @close="close" customStyle="overflow-y: scroll;overscroll-behavior: none">
			<view style="padding: 30rpx;max-height:800rpx;">
				<image src="http://applet.atptest.com/lzc2023082801.jpg" mode="widthFix" style="width: 100%;"></image>
			</view>
		</u-popup>

		<u-popup :show="show1" :round="30" @close="close" customStyle="overflow-y: scroll;overscroll-behavior: none">
			<view style="padding: 30rpx;max-height:800rpx;">
				<image src="http://applet.atptest.com/lzc2023082802.jpg" mode="widthFix" style="width: 100%;"></image>
			</view>
		</u-popup>

		<!-- 跳转提示弹出层 -->
		<u-popup :show="disabledTo" :round="10" mode="center" @close="close">
			<view style="padding: 30rpx;">
				<text v-text="`此单为月结订单,${numTo}秒后自动跳转...`"></text>
			</view>
		</u-popup>

		<!-- 自行邮寄 -->
		<u-popup :show="showSelf" :round="30" @close="close(1)">
			<view class="popup">
				<view style="text-align: center;">自行邮寄</view>
				<view class="addressBox">
					<view class="card" style="border-bottom: 1px dashed #E9E9E9;">
						<view>
							<view class="top">寄</view>
						</view>
						<view class="address">
							<view><text class="name">鹏城测试ATP Lab</text><text class="phone">15914178852</text></view>
							<view class="addressR">广东省深圳市福田区振华路163号飞亚达大厦102-C室</view>
						</view>
						<view class="bottom" @click="copybtn()"><text style="color: #A80000;">复制</text>
						</view>
					</view>
					<view class="card">
						<view>
							<view class="top" style="background-color: #FD3B39;">回</view>
						</view>
						<view class="address" v-if="formData.regularAddress.name">
							<view><text class="name">{{formData.regularAddress.name}}</text><text
									class="phone">{{formData.regularAddress.phone}}</text></view>
							<view class="addressR">{{formData.regularAddress.address}}</view>
						</view>
						<view class="address" v-else style="display: flex;align-items: center;color: #576FD3;"
							@click="selectAddress()">点击新增回寄地址</view>
						<view class="bottom" @click="selectAddress()">
							<text>地址簿</text>
						</view>
					</view>
				</view>
				<view style="color: #A80000;font-size: 24rpx;margin-left: 10px;margin-top: 4px;">此地址为检测订单完成后，检测机构寄回件地址
				</view>

				<view class="addressBox">
					<view class="ticket_container">
						<view class="form_item">
							<view class="label">快递公司</view>
							<view class="item_input">
								<u--input placeholder="请填写" border="none" v-model="formData.expressCompany"
									inputAlign="right" fontSize="12"
									placeholder-style="text-align: right;color: rgb(167, 167, 167);font-size: 24rpx;">
								</u--input>
							</view>
						</view>
						<view class="form_item">
							<view class="label">运单号码</view>
							<view class="item_input">
								<u--input placeholder="请填写" border="none" v-model="formData.waybillNo"
									inputAlign="right" fontSize="12"
									placeholder-style="text-align: right;color: rgb(167, 167, 167);font-size: 24rpx;">
								</u--input>
							</view>
						</view>
					</view>
				</view>
				<button style="color: #fff;background-color: #3953b8;margin-top: 20rpx;" @click="close(1)">确认</button>
			</view>
		</u-popup>

		<!-- 到店检测 -->
		<u-popup :show="showArrive" :round="30" @close="close(2)">
			<view class="popup">
				<view style="text-align: center;">到店检测</view>
				<view class="addressBox">
					<view class="card">
						<view>
							<view class="top" style="background-color: #FD3B39;">回</view>
						</view>
						<view class="address" v-if="formData.regularAddress.name">
							<view>
								<text class="name">{{formData.regularAddress.name}}</text>
								<text class="phone">{{formData.regularAddress.phone}}</text>
							</view>
							<view class="addressR">{{formData.regularAddress.address}}</view>
						</view>
						<view class="address" v-else style="display: flex;align-items: center;color: #576FD3;"
							@click="selectAddress()">点击新增回寄地址
						</view>
						<view class="bottom" @click="selectAddress()">
							<text>地址簿</text>
						</view>
					</view>
				</view>
				<view style="color: #A80000;font-size: 24rpx;margin-left: 10px;margin-top: 4px;">此地址为检测订单完成后，检测机构寄回件地址
				</view>
				<button style="color: #fff;background-color: #3953b8;margin-top: 20rpx;" @click="close(2)">确认</button>
			</view>
		</u-popup>

		<!-- 预约时间 -->
		<u-popup :show="reserveTimeFlag" :round="20" @close="close(3)" @touchmove.stop.prevent="stopPenetrate"
			zIndex="99">
			<u-toast ref="uToastReserveTime"></u-toast>
			<view class="time_popup">
				<view class="time_label">
					<text>送货时间</text>
					<view class="time_tip">若无号，可以选择是否加急进行订单插队处理</view>
				</view>
				<view class="period_container">
					<view class="period_left">
						<scroll-view class="time_period" scroll-y="true" :enhanced="true" :show-scrollbar="true">
							<view class="left_item" v-for="(item,index) in reserveTimeList" :key="item.value"
								@click="selectDate(item,index)"
								:style="{boxShadow: item.status == 1 ? (item.state != 1 ? '-1px 1px 4px 0px rgba(0, 0, 0, 0.25)' : '') : '',color: item.state == 1 ? '#C9C9C9':'#000'}">
								{{item.value.slice(5)}}
							</view>
						</scroll-view>
					</view>
					<view class="period_right">
						<scroll-view class="time_period" scroll-y="true" :enhanced="true" :show-scrollbar="true">
							<u-radio-group v-model="reservationID" placement="column">
								<view v-for="(item, index) in timePeriodList" :key="index">
									<view class="period_item">
										<u-radio :name="item.id" :disabled="item.state != 0"></u-radio>
										<view class="period_item_label">
											<view>{{item.value}}</view>
											<view style="color: #7C8083;">{{ getStateValue(item.state)}}</view>
										</view>
									</view>
								</view>
							</u-radio-group>
						</scroll-view>
					</view>
				</view>
				<view class="pay_container">
					<button @click="formSubmit" :disabled="btnDisabled"
						class="pay_btn">立即支付（￥{{formData.total}}）</button>
				</view>
			</view>
		</u-popup>

		<!-- 优惠券弹框 -->
		<u-popup :show="couponFlag" mode="bottom" :round="10"
			customStyle="overflow-y: scroll;overscroll-behavior: none">
			<view class="coupon_pop">
				<Coupon :couponList="couponList" :checkedIds="checkedIds" :totalPrice="formData.total" :reload="reload"
					@changeCoupon="changeCoupon" />
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Coupon from "../discountSelect/discountSelect.vue"
	import {
		mapMutations
	} from 'vuex'
	import {
		GetCommodityList,
		GetReportCE,
		CreateOrder,
		GetUserByOpenid,
		GetUserInfo,
		GetOrderToken,
		GetCalendar,
		GetReservation
	} from '../../../api/user.js'
	import {
		producerSearch,
		brandSearch
	} from '../../../api/search.js'
	import {
		Find,
		Check
	} from '../../../api/balance.js'
	import {
		getDefaultAddress,
		getAddressInfo
	} from '@/api/address.js'
	import FuzzyList from "@/components/fuzzy-list/fuzzy-list.vue"
	import debounce from '@/utils/debounce.js'; //防抖函数
	import {
		getFutureDate,
	} from "../../../utils/dayjs.js"
	export default {
		components: {
			FuzzyList,
			Coupon
		},
		data() {
			return {
				rules: {
					// 必填验证
					'client': {
						required: true,
						message: '委托方不能为空',
						trigger: ['blur', 'change']
					},
					// 'model': [
					// 	{
					// 		required: true,
					// 		message: '型号不能为空',
					// 		trigger: ['blur', 'change']
					// 	},
					// 	// 正则判断为字母或数字
					// 	{
					// 		pattern: /^[^\u4e00-\u9fa5]+$/,
					// 		// 正则检验前先将值转为字符串
					// 		transform(value) {
					// 			return String(value);
					// 		},
					// 		message: '型号不能包括汉字'
					// 	},
					// ],
					'purchaseOrderNo': {
						required: true,
						message: '采购单号不能为空',
						trigger: ['blur', 'change']
					},
					'sCount': [{
							type: 'number',
							required: true,
							message: '送检数量不能为空',
							trigger: ['blur', 'change']
						},
						// 正则判断为字母或数字
						{
							pattern: /^\+?[1-9][0-9]*$/,
							// 正则检验前先将值转为字符串
							transform(value) {
								return String(value);
							},
							message: '送检数量不能为0'
						}
					],
				},
				formData: {
					brandName: '',
					model: '',
					batch: '',
					supplier: '',
					client: '',
					production: '',
					purchaseOrderNo: '',
					sCount: '',
					remark: '',
					state: '',
					commodityId: [],
					jsonData: [],
					reportDto: [],
					regularAddress: {
						address: "",
						name: "",
						phone: ""
					}, //回寄地址
					addressType: null, //寄件方式
					waybillNo: "", //运单号
					expressCompany: "",
					total: 0,
				},
				reservationTime: "",
				reservationID: -1,
				mailType: [{
						name: '自行邮寄',
						text: "需自行填写快递单进行发货",
						id: 1
					},
					{
						name: '到店检测(寄回)',
						text: "需自行前往检测公司，检测完成后会寄回到您的回寄地址",
						id: 2
					},
					{
						name: '到店检测(自提)',
						text: "需自行前往检测公司，检测完成后需要您自行取货",
						id: 4
					}
				],
				//报告类型
				reportType: [],
				//报告
				reportTypeValue: null,
				reportPrice: 0,
				itemPrice: 0,
				//检测项目
				checkbox: [],
				checkedIds: [],
				// 订单号
				orderNo: '',
				//判断 采购单号 及 支付
				role: {},
				//协议勾选
				readValue: null,
				//寄件方式
				showSelf: false,
				showArrive: false,
				// 倒计时2
				timerTo: null,
				numTo: 3,
				disabledTo: false,
				// 协议弹出层
				show: false,
				show1: false,
				//下单按钮禁用
				btnDisabled: false,
				// 品牌 产地下拉框
				showFuzzy: false,
				//选择预约时间弹框
				reserveTimeFlag: false,
				//选择优惠券弹框
				couponFlag: false,
				couponList: [],
				listFuzzy: [],
				showFuzzyP: false,
				listFuzzyP: [],
				couponIds: [],
				appointmentStatus: null,
				// 当前时间及未来六天时间
				reserveTimeList: [{
						value: getFutureDate(0),
						state: 0,
						status: 0
					},
					{
						value: getFutureDate(1),
						state: 0,
						status: 0
					},
					{
						value: getFutureDate(2),
						state: 0,
						status: 0
					},
					{
						value: getFutureDate(3),
						state: 0,
						status: 0
					},
					{
						value: getFutureDate(4),
						state: 0,
						status: 0
					},
					{
						value: getFutureDate(5),
						state: 0,
						status: 0
					},
					{
						value: getFutureDate(6),
						state: 0,
						status: 0
					},

				],
				timePeriodList: [{
						value: "10:00-11:00",
						state: 1
					},
					{
						value: "11:00-12:00",
						state: 2
					},
					{
						value: "13:30-15:00",
						state: 1
					},
					{
						value: "15:00-16:00",
						state: 0
					},
					{
						value: "16:00-17:00",
						state: 0
					},
					{
						value: "17:00-18:00",
						state: 0
					},
					{
						value: "18:00-19:00",
						state: 0
					},
				],
				timePeriod: "",
				deliveryTime: "",
				reservedTime: [],
				//是否加急
				isUrgentFlag: false,
				reload: false,
				couponType: -1,
				discounts: 0
			};
		},

		onLoad(options) {
			console.log("调用onLoad了", options);
			if (options.couponIds) {
				this.couponIds = JSON.parse(options.couponIds)
				console.log("couponIds", this.couponIds);
			} else {
				this.couponIds = []
			}
			this.reservationID = -1
			// 获取检测项目
			this.getList()
			this.getUserInfo()
			this.getUserByOpenid()
			//获取报告费用
			this.getReportCE()
			this.getDefaultAddress()
		},

		onShow() {
			this.reserveTimeList.forEach(item => {
				this.getHoliday(item)
			})
			this.getUserInfo()
			this.getOrderToken()
			this.getCouponList({
				pageIndex: 1,
				pageSize: 999,
			})
		},

		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form.setRules(this.rules)
		},

		methods: {
			...mapMutations('user', ['setToken']),

			//优惠券列表
			async getCouponList(data) {
				const res = await Find(data)
				this.couponList = res.items
				console.log("调用优惠券列表", this.couponList);
			},

			// 优惠券弹框
			toDiscount() {
				this.couponFlag = true;
				this.getCouponList({
					pageIndex: 1,
					pageSize: 999,
				})
				this.getTotalPrice()

				let checkIds = this.checkbox.map(item => {
					if (item.amount > 0) {
						return item.id
					}
				})
				this.checkedIds = checkIds.filter(item => {
					return item
				})
				console.log("this.checkedIds", this.checkedIds);
			},

			//选择优惠券
			changeCoupon(val) {
				this.getTotalPrice()
				console.log("优惠券", val);
				this.reload = val.reload
				this.couponType = val.couponType
				this.discounts = val.discounts
				this.formData.couponsIds = val.couponsIds ? val.couponsIds : []
				if (val.discounts) {
					this.formData.total = Number(this.formData.total) - Number(val.discounts)
				}
				if (val.freeIds.length) {
					for (let i = 0; i < val.freeIds.length; i++) {
						for (let j = 0; j < this.checkbox.length; j++) {
							if (val.freeIds[i] == this.checkbox[j].id) {
								this.formData.total = Number(this.formData.total) - (this.checkbox[j].amount * this
									.checkbox[j]
									.price)
							}
						}
					}
				}
				console.log("总价", this.formData.total);
				this.couponFlag = false
			},

			// 获取用户身份
			getUserByOpenid() {
				GetUserByOpenid().then((res) => {
					this.role = res
				})
			},

			//预约时间状态转换成中文
			getStateValue(val) {
				switch (val) {
					case 1:
						return "已被预定"
					case 2:
						return "已过期"
				}
			},

			//根据日期获取预约时间段
			async getReservation() {
				const res = await GetReservation({
					time: this.deliveryTime
				})
				if (res && res.length > 0) {
					this.timePeriodList = res
				} else {
					uni.showToast({
						title: "接口异常",
						icon: 'error'
					})
					this.timePeriodList = []
				}
			},

			//判断日期是工作日/非工作日
			async getHoliday(item) {
				const res = await GetCalendar({
					time: item.value
				})
				if (res == 0 || res == 1 || res == 2 || res == 3) {
					if (res != 0) {
						item.state = 1
						item.status = 1
					}
				} else {
					uni.showToast({
						title: "接口异常",
						icon: 'error'
					})
					this.reserveTimeList = []
				}
			},

			// 获取用户信息
			getUserInfo() {
				GetUserInfo().then((res) => {
					this.formData.client = res.wxName
					this.appointmentStatus = res.appointmentStatus
					if (this.appointmentStatus == 0) {
						this.isUrgentFlag = true
					}
				})
			},

			//获取订单token
			async getOrderToken() {
				const res = await GetOrderToken()
			},

			//选择时间
			showReserveTime() {
				this.reserveTimeFlag = true
				for (let i = 0; i < this.reserveTimeList.length; i++) {
					if (this.reserveTimeList[i].state == 0) {
						this.reserveTimeList[i].status = 1
						this.deliveryTime = this.reserveTimeList[i].value
						this.reservationTime = this.reserveTimeList[i].value.split("-").join("")
						this.getReservation()
						return
					}
				}
			},

			//点击日期获取时间段
			selectDate(val, index) {
				if (val.state != 1) {
					this.reserveTimeList.forEach(item => {
						item.status = 0
					})
					this.reservationID = -1
					val.status = 1
					this.deliveryTime = val.value
					this.reservationTime = val.value.split("-").join("")
					this.getReservation()
				}
			},

			// 调起通知
			subscribe() {
				const _that = this
				uni.getSetting({
					withSubscriptions: true,
					success: (res) => {
						if (!res.subscriptionsSetting.mainSwitch) {
							uni.showModal({
								title: '提示',
								content: '为了及时获取订单状态，您是否想接收订单状态的消息提醒？',
								success: function(res) {
									if (res.confirm) {
										// 订阅消息的总开关,如果是关着的，引导用户去打开
										_that.openMessage()
									} else if (res.cancel) {
										//创建订单
										_that.uploadOrder();
									}
								}
							});
						} else {
							// 如果开着，则继续向下打开弹窗，获取用户授权
							_that.message()
						}
					},
					fail() {
						// 如果失败，也打开弹窗，获取用户授权
						_that.message()
					}
				})
			},

			// 调用通知
			message() {
				const _that = this
				uni.requestSubscribeMessage({
					//此处填写刚才申请模板的模板ID
					tmplIds: ['HDW7cwWuKtvWeppBNzrnQiejfi3j18buPzd6lF4CoGs',
						'Xy1xuuzGcV0R5P8Pv8xq7EPb8gHTZAiFwH9OqIM18l0'
					],
					success(res) {
						console.log("调用");
						//创建订单
						_that.uploadOrder();
					},
					fail(res) {
						console.log(res);
					}
				})
			},

			// 引导用户开启订阅
			openMessage() {
				const _that = this
				uni.openSetting({
					withSubscriptions: true,
					complete: (res) => {
						//创建订单
						_that.uploadOrder();
					}
				})
			},

			// 获取检测项目
			async getList() {
				const res = await GetCommodityList()
				if (res) {
					this.checkbox = res
					this.checkbox.forEach(item => item.total = 0)
					//如果使用优惠券下单，将优惠项目数量设置为1
					// if (this.couponIds.length > 0) {
					// 	for (let i = 0; i < this.couponIds.length; i++) {
					// 		for (let j = 0; j < this.checkbox.length; j++) {
					// 			if (this.couponIds[i] == this.checkbox[j].id) {
					// 				this.checkbox[j].amount = 1
					// 				this.checkbox[j].total = Number(this.checkbox[j].amount) * Number(this.checkbox[j]
					// 					.price)
					// 			}
					// 		}
					// 	}
					// 	this.getTotalPrice()
					// }
				}
			},

			//获取报告费用
			async getReportCE() {
				const res = await GetReportCE()
				if (res) {
					this.reportType = res
				}
				if (this.couponIds.length > 0) {
					this.checkboxChange(this.couponIds)
				}
			},

			// 提交按钮
			formSubmit() {
				// 月结
				if (this.role.state) {
					this.formData.state = 9
				} else {
					this.formData.state = 2
				}
				this.formData.brandName = this.formData.brandName.trim()
				this.formData.batch = this.formData.batch.trim()
				this.formData.client = this.formData.client.trim()
				this.formData.model = this.formData.model.trim()
				this.formData.production = this.formData.production.trim()
				this.formData.purchaseOrderNo = this.formData.purchaseOrderNo.trim()
				this.formData.supplier = this.formData.supplier.trim()
				let arr = this.checkbox.filter(item => {
					return item.amount > 0
				})
				let arr1 = arr.map((item) => {
					return {
						name: item.name,
						price: item.price,
						amount: item.amount,
						profit: item.profit
					}
				})
				this.formData.commodityId = arr.map((item) => {
					return item.id
				})
				this.formData.jsonData = arr1

				//formdata数据校验
				if (!this.isUrgentFlag) {
					if (this.readValue != 1) {
						this.$refs.uToastReserveTime.show({
							message: '请先勾选服务协议',
						})
						return
					}
					if (this.formData.commodityId.length < 1) {
						this.$refs.uToastReserveTime.show({
							message: '请选择检测项目'
						})
						return
					}
					if (this.formData.client == "") {
						this.$refs.uToastReserveTime.show({
							message: '委托方不能为空'
						})
						return
					}
					if (this.formData.regularAddress.address == "" && this.formData.addressType != 4) {
						this.$refs.uToastReserveTime.show({
							message: '请填写回寄地址'
						})
						return
					}
					if (this.formData.addressType == null) {
						this.$refs.uToastReserveTime.show({
							message: '请选择寄件方式'
						})
						return
					}
					if (this.formData.addressType == null) {
						this.$refs.uToastReserveTime.show({
							message: '请选择寄件方式'
						})
						return
					}
					if (this.reservationID == -1) {
						this.$refs.uToastReserveTime.show({
							message: '请选择送货时间段'
						})
						return
					}
				} else {
					if (this.readValue != 1) {
						this.$refs.uToast.show({
							message: '请先勾选服务协议',
						})
						return
					}
					if (this.formData.commodityId.length < 1) {
						this.$refs.uToast.show({
							message: '请选择检测项目'
						})
						return
					}
					if (this.formData.client == "") {
						this.$refs.uToast.show({
							message: '委托方不能为空'
						})
						return
					}
					if (this.formData.regularAddress.address == "" && this.formData.addressType != 4) {
						this.$refs.uToast.show({
							message: '请填写回寄地址'
						})
						return
					}
					if (this.formData.addressType == null) {
						this.$refs.uToast.show({
							message: '请选择寄件方式'
						})
						return
					}
				}
				this.$refs.form.validate().then(res => {
					this.subscribe()
				}).catch(err => {
					if (!this.isUrgentFlag) {
						this.$refs.uToastReserveTime.show({
							message: err[0].message
						})
					} else {
						this.$refs.uToast.show({
							message: err[0].message
						})
					}
				})
			},

			//创建订单
			uploadOrder() {
				this.btnDisabled = true
				uni.showLoading({
					title: '加载中',
				});
				if (!this.isUrgentFlag) {
					this.formData.reservationID = this.reservationID
					this.formData.reservationTime = this.reservationTime
				} else {
					this.formData.urgent = 1
				}
				CreateOrder(this.formData).then((res) => {
						console.log("信息", res);
						if (res.code && res.code != 200) {
							uni.showToast({
								title: res.message,
								icon: 'error'
							})
						} else {
							// 订单号
							this.orderNo = res.orderNo
							if (this.formData.state == 9) {
								this.sendTimerTo()
							} else {
								// 跳转待支付详情页
								uni.redirectTo({
									url: `/pagesA/pages/payOrder/payOrder?i=${this.orderNo}`
								})
							}
						}
						// 上传成功清空表单数据 启用支付按钮
						this.btnDisabled = false
						uni.hideLoading();
					})
					.catch((res) => {
						// 启用支付按钮
						this.btnDisabled = false
						uni.hideLoading();
						uni.showToast({
							title: '请求出错了~',
							icon: 'error'
						})
						//打开创建订单权限
						this.getOrderToken()
					})
			},

			// 关闭弹出层
			close(i) {
				if (i) {
					if (i == 1 || i == 2) {
						if (i == 1) {
							this.formData.addressType = 1
						} else if (i == 2) {
							this.formData.addressType = 2
						}
						if (this.formData.regularAddress.address == "") {
							this.$refs.uToast.show({
								message: '回寄地址未填写'
							})
						}
					}
					if (i == 3) {
						this.reserveTimeFlag = false
					}
				}
				this.show = false
				this.show1 = false
				this.showArrive = false
				this.showSelf = false
			},

			//弹框滑动页面穿透问题
			stopPenetrate() {
				return
			},

			// 打开弹出层
			openClick(i) {
				if (i == 1) {
					//到店检测
					this.showArrive = true
					if (!this.formData.regularAddress.address) {
						this.getDefaultAddress()
					}
				} else if (i == 0) {
					//自行邮寄
					this.showSelf = true
					if (!this.formData.regularAddress.address) {
						this.getDefaultAddress()
					}
				} else if (i == 2) {
					this.formData.regularAddress = {
						address: "",
						name: "",
						phone: ""
					}
				} else if (i == 8) {
					this.show = true
				} else {
					this.show1 = true
				}
			},

			//复选框
			checkboxChange(e) {
				let arr = this.reportType.filter((item) => {
					return e.includes(item.id)
				})
				this.formData.reportDto = arr.map((item) => {
					return {
						id: item.id,
						name: item.name,
						price: item.price,
					}
				})
				this.reportPrice = 0;
				arr.forEach(item => {
					this.reportPrice += item.price
				})
				this.formData.total = (this.itemPrice + this.reportPrice).toFixed(2)
				this.reportTypeValue = arr.map(item => {
					return item.id
				})
				console.log(this.formData.reportDto);
				//如果勾选加急，直接支付，没有勾选就选择预约时间
				if (e.includes(10) && this.appointmentStatus == 1) {
					this.isUrgentFlag = true
					this.reservationID = -1
					this.reservationTime = ""
				} else {
					if (this.appointmentStatus == 1) {
						this.isUrgentFlag = false
					} else {
						this.isUrgentFlag = true
						this.reservationID = -1
						this.reservationTime = ""
					}
				}
			},

			//月结倒计时
			sendTimerTo() {
				this.numTo = 3
				this.disabledTo = true
				this.loadingTo(); //启动定时器
				this.timerTo = setInterval(() => {
					//创建定时器
					if (this.numTo === 1) {
						this.clearTimerTo(); //关闭定时器
					} else {
						this.loadingTo();
					}
				}, 1000);
			},

			loadingTo() {
				//启动定时器
				this.numTo--; //定时器减1
			},

			clearTimerTo() {
				//清除定时器
				clearInterval(this.timerTo);
				this.timerTo = null;
				this.numTo = '';
				this.disabledTo = false
				// uni.navigateTo({
				// 	url: '/pagesB/pages/order/order?i=3'
				// })
			},

			//数量减
			decreaseNum(item) {
				if (item.amount > 0) {
					item.amount--
					item.total = Number(item.amount) * Number(item.price)
					this.getTotalPrice()
				}
				this.reload = true
				this.couponType = -1
				this.discounts = 0
			},

			//数量加
			addNum(item) {
				item.amount++;
				item.total = Number(item.amount) * Number(item.price)
				this.getTotalPrice()
				this.reload = true
				this.couponType = -1
				this.discounts = 0
			},

			// 计算总价
			getTotalPrice() {
				this.itemPrice = 0
				this.checkbox.forEach(item => {
					this.itemPrice += item.total
				})
				this.formData.total = (this.itemPrice + this.reportPrice).toFixed(2)
			},

			//一键复制
			copybtn() {
				uni.setClipboardData({
					data: "鹏城测试ATP Lab 广东省深圳市福田区振华路163号飞亚达大厦102-C室 15914178852", //要被复制的内容
					success: () => { //复制成功的回调函数
						uni.showToast({ //提示
							title: '复制成功'
						})
					}
				});
			},

			// 更换地址
			selectAddress() {
				// 跳转到地址页面
				uni.navigateTo({
					url: `/pagesA/pages/address/address?type=addInvoice`
				})
			},

			//地址传递
			prevDateFun(object) {
				console.log("调用了");
				let _this = this
				if (object) {
					_this.getAddressInfo(object.addressId)
				} else {
					return
				}
			},

			// 获取默认地址
			async getDefaultAddress() {
				const res = await getDefaultAddress()
				this.formData.regularAddress.address = res.province + res.city + res.disCoun.split(",")[0] + res
					.detaAddress
				this.formData.regularAddress.name = res.conPer
				this.formData.regularAddress.phone = res.phoneNumber
			},

			// 根据id获取地址信息
			async getAddressInfo(val) {
				let list = {
					id: Number(val)
				}
				const res = await getAddressInfo(list)
				console.log("回显地址", res);
				this.formData.regularAddress.address = res.province + res.city + res.disCoun.split(",")[0] + res
					.detaAddress
				this.formData.regularAddress.name = res.conPer
				this.formData.regularAddress.phone = res.phoneNumber
			},


			//品牌下拉框
			inputBrand() {
				debounce(this.getListFuzzy(), 900);
			},
			focusBrand() {
				debounce(this.getListFuzzy(), 900);
			},
			blurBrand() {
				this.showFuzzy = false;
			},

			//获取下拉品牌列表
			getListFuzzy() {
				const {
					formData
				} = this;
				/** 输入框内有值就进行搜索，没有值就关闭 */
				if (formData.brandName) {
					brandSearch(formData.brandName).then(resp => {
						this.listFuzzy = resp.items;
						if (!this.showFuzzy) this.showFuzzy = true;
					});
				} else {
					this.showFuzzy = false;
				}
			},

			//选中品牌下拉值
			selectFuzzy(event) {
				this.showFuzzy = false;
				this.formData.brandName = event.brandName;
			},

			//产地下拉框
			inputBrandP() {
				debounce(this.getListFuzzyP(), 500);
			},
			focusBrandP() {
				debounce(this.getListFuzzyP(), 900);
			},
			blurBrandP() {
				this.showFuzzyP = false;
			},

			//获取下拉品牌列表
			getListFuzzyP() {
				const {
					formData
				} = this;
				/** 输入框内有值就进行搜索，没有值就关闭 */
				if (formData.production) {
					producerSearch(formData.production).then(resp => {
						this.listFuzzyP = resp.items;
						if (!this.showFuzzyP) this.showFuzzyP = true;
					});
				} else {
					this.showFuzzyP = false;
				}
			},

			//选中品牌下拉值
			selectFuzzyP(event) {
				this.showFuzzyP = false;
				this.formData.production = event.producerName;
			},

		},


	}
</script>

<style lang="scss" scoped>
	// 处理 u-popup 组件层级过高,将 uni.showToast 覆盖问题
	/deep/ .u-transition.u-fade-enter-to.u-fade-enter-active {
		z-index: 98 !important;
	}

	.test {
		image {
			width: 100%;
		}

		.load {
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.main {
			padding: 0 20rpx;
			padding-bottom: 20rpx;

			.table {
				border: 1px solid #8D8D8D;
				margin-top: 40rpx;

				.head {
					background-color: #e2e2e3;
					text-align: center;
					font-weight: 700;
					padding: 3px 0;
				}

				.body {
					display: flex;
					align-items: center;

					view {
						height: 90rpx;
						width: 50%;
						padding: 0 20rpx;
						border-top: 1px solid #8D8D8D;
					}

					view:first-child {
						border-right: 1px solid #8D8D8D;
					}
				}

				.body1 {
					display: flex;
					flex-wrap: wrap;

					.fristChild {
						display: flex;
						align-items: center;
						font-size: 24rpx;
						height: 70rpx;
						width: 100%;
						padding: 10rpx;
						border-bottom: 1px solid #8D8D8D;
						box-sizing: border-box;

						.name {
							width: 40%;
							padding-right: 10rpx;
						}

						.price {
							width: 30%;
						}

						.number {
							flex: 1;
							display: flex;
							justify-content: space-evenly;
							align-items: center;
							font-size: 28rpx;
						}
					}

					.secondChild {
						display: flex;
						align-items: center;
						font-size: 24rpx;
						height: 70rpx;
						width: 100%;
						padding: 10rpx;
						border-bottom: 1px solid #8D8D8D;
						box-sizing: border-box;
					}

					.note {
						display: flex;
						align-items: center;
						width: 100%;
						font-size: 24rpx;
						line-height: 40rpx;
						height: 50rpx;
						padding: 10rpx;

						view:last-child {
							flex: 1;
						}
					}
				}
			}

			.mailType {
				margin-top: 20rpx;

				.box {
					display: flex;
					justify-content: space-between;
					align-items: center;
					background-color: #ecebeb;
					margin: 10rpx 0;
					padding: 20rpx 50rpx;
					border-radius: 10rpx;
				}
			}

			.coupon_container {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin: 40rpx 0rpx;
				box-sizing: border-box;

				.bargain_btn {
					background-color: #3e56ba;
					color: #fff;
				}
			}
		}

		.coupon_pop {
			height: 800rpx;
		}

		.submit {
			color: #fff;
			margin-top: 20rpx;
		}

		.popup {
			padding: 30rpx;
			background-color: #f4f4f4;
			border-top-left-radius: 60rpx;
			border-top-right-radius: 60rpx;

			.addressBox {
				margin-top: 10px;
				border-radius: 10px;
				background-color: #fff;

				.card {
					display: flex;
					font-size: 24rpx;
					margin-top: 10px;
					padding: 10px;

					.top {
						background-color: #000;
						color: #fff;
						border-radius: 50%;
						width: 25px;
						height: 25px;
						text-align: center;
						line-height: 25px;
					}

					.address {
						width: 65%;
						margin: 0 10px;

						.name {
							font-size: 30rpx;
							font-weight: 700
						}

						.phone {
							padding-left: 10rpx;
							color: #787878
						}

						.addressR {
							color: #787878;
							margin-top: 10rpx
						}
					}

					.bottom {
						flex: 1;
						display: flex;
						justify-content: center;
						align-items: center;

						text {
							width: 100%;
							text-align: center;
							border-left: 2px solid #E9E9E9;
						}
					}
				}

				.ticket_container {
					width: 100%;
					height: 160rpx;
					box-sizing: border-box;
					padding: 0 26rpx;
					display: flex;
					flex-direction: column;
					justify-content: space-around;
					margin-top: 20rpx;

					.form_item {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.label {
							color: rgb(61, 61, 61);
							font-family: 思源黑体;
							font-size: 28rpx;
							font-weight: 400;
						}

						.item_input {
							width: 80%;

							.form_select {
								color: rgb(167, 167, 167);
								font-family: 思源黑体;
								font-size: 24rpx;
								font-weight: 400;
								text-align: right;
							}
						}
					}
				}
			}
		}

		.time_popup {

			.time_label {
				height: 142rpx;
				padding-left: 32rpx;
				box-sizing: border-box;
				color: rgb(30, 30, 30);
				font-family: 思源黑体;
				font-size: 36rpx;
				font-weight: 500;
				display: flex;
				flex-direction: column;
				justify-content: center;

				.time_tip {
					color: rgb(201, 0, 0);
					font-family: 思源黑体;
					font-size: 24rpx;
					font-weight: 500;
					margin-top: 12rpx;
				}
			}


			.period_container {
				height: 746rpx;
				border-top: 1px solid rgb(235, 237, 236);
				border-bottom: 1px solid rgb(235, 237, 236);
				display: flex;

				.period_left {
					width: 204rpx;
					height: 746rpx;
					border-right: 1px solid rgb(235, 237, 236);
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.time_period {
						width: 100%;
						height: 746rpx;
					}

					.left_item {
						height: 107rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						color: rgb(63, 63, 63);
						font-family: 思源黑体;
						font-size: 36rpx;
						font-weight: 400;
					}
				}

				.period_right {
					flex: 1;

					.time_period {
						width: 100%;
						height: 746rpx;

						.period_item {
							display: flex;
							align-items: center;
							border-bottom: 1px solid rgb(235, 237, 236);
							padding-left: 40rpx;
							box-sizing: border-box;
						}

						.period_item_label {
							width: 100%;
							display: flex;
							align-items: center;
							justify-content: space-between;
							height: 106rpx;
							padding-right: 32rpx;
							box-sizing: border-box;
							color: rgb(51, 51, 51);
							font-family: 思源黑体;
							font-size: 36rpx;
							font-weight: 400;
						}
					}
				}
			}

			.pay_container {
				width: 100%;
				z-index: 99;

				.pay_btn {
					width: 95%;
					color: #fff;
					background-color: #3953b8;
					margin: 20rpx auto 0 auto;
				}
			}
		}
	}

	/deep/.u-form-item__body__right__message {
		display: none;
	}

	/deep/ .u-form-item__body__left__content__label {
		font-size: 24rpx !important;
	}

	/deep/ .u-input__content__field-wrapper__field {
		font-size: 24rpx !important;
	}
</style>